<template>
	<view class="content">

		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="stopPrevent" @click="toggleSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer attr-content" @click.stop="stopPrevent">
				<view class="a-t">
					<image :src="goodsInfoNew.thumb || goodsInfo.thumb"></image>
					<view class="right">
						<text class="price" v-if="orderType==1">¥{{seckillPrice/100}}</text>
						<text class="price" v-else>¥{{ goodsInfoNew.price || goodsInfo.price }}</text>
						<text class="stock">库存：{{ goodsInfoNew.stock || goodsInfo.stock }}件</text>
						<view class="selected">
							<text>{{ skutitlename }}</text>
						</view>
					</view>
				</view>
				<view class="count">
					<view class="title">数量</view>
					<view class="function">
						<!-- <uni-number-box></uni-number-box> -->
						<uni-number-box v-if="orderType==0" :min="1" :max="99" v-model="count" @bindChange="countUpdate"></uni-number-box>
						<uni-number-box v-else :min="1" :max="1" v-model="count" @bindChange="countUpdate"></uni-number-box>
						<!-- <uni-number-box @change="bindChange"></uni-number-box> -->
					</view>
				</view>
				<!-- specificationBtn(oItem.spec_value_id, n, index, isShows[n][index], ProductItem.spec_name) -->
				<view v-for="(ProductItem, n) in gspecList.spec_info_list" :key="n" class="attr-list">
					<text>{{ ProductItem.spec_name }}</text>
					<view class="item-list">
						<text v-for="(oItem, index) in ProductItem.value"
							@click="specificationBtn(oItem.spec_value_id, n, index, isShows[n][index], ProductItem.spec_name)"
							:key="index" class="tit"
							:class="[isShows[n][index] ? '' : 'noneActive', subIndex[n] == index ? 'selected' : '']">
							{{oItem.spec_value_name}}

						</text>
					</view>
				</view>
				<view class="buttons">
					<view class="btn-join" @click='submitnew("join")' v-if="orderType==0">加入购物车</view>
					<view class="btn-buy" @click='submitnew("buy")'>购 买</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	export default {

		props: {
			gspecList: {

			},
			goodsInfo: {

			},
			product: '',

		},
		data() {
			return {
				specClass: 'none', //规格弹窗是否显示
				goodsInfoNew: {}, //当规格选择完成时重新覆盖商品信息
				skutitlename: '', //提示用户例如：请选择温度，口味；或者提示用户已选择温度，口味
				skutitlenamelist: [], //存储规格标题
				selectArr: [], //存放被选中的值
				shopItemInfo: {}, //存放要和选中的值进行匹配的数据
				subIndex: [], //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
				skuId: '', //规格id
				isShows: [],
				count: 1,
				orderType: 0, //0 是普通商品 1是立即抢购 2是积分兑换
				seckillPrice:0,//抢购的价格
			};
		},

		onLoad() {

		},
		beforeUpdate() {

		},
		updated() {

		},
		mounted() {

		},
		created() {

		},
		methods: {

			test1(id, pindex) {

			},
			setOrderType(index) {
				this.orderType = index
				if(index==1){
					this.seckillPrice=uni.getStorageSync('seckillPrice')||0
				}
			},
			// 选择规格
			specificationBtn: function(id, pindex, index, disable, pname) {

				var self = this;
				if (!disable) {
					return '';
				}
				// console.log(self.selectArr[pindex] +"："+ id)


				if (self.selectArr[pindex] != id) {
					self.selectArr[pindex] = id;
					self.subIndex[pindex] = index;
					self.skutitlenamelist[pindex] = ''; //

				} else {
					if (self.subIndex[0] == -1) {
						self.selectArr[pindex] = id;
						self.subIndex[pindex] = index;
						self.skutitlenamelist[pindex] = ''; //
					} else {
						self.selectArr[pindex] = '';
						self.subIndex[pindex] = -1; //去掉选中的颜色

						self.skutitlenamelist[pindex] = pname; //
					}
				}
				// console.log(self.selectArr[pindex] +"："+ id)
				self.checkItem();


			},
			// 处理数据
			checkItem: function() {
				var option = this.gspecList.spec_info_list;
				var result = []; //定义数组存储被选中的值
				// console.log("option")
				// console.log(JSON.stringify(option))
				for (let i = 0; i < option.length; i++) {
					result[i] = this.selectArr[i] ? this.selectArr[i] : '';
				}
				for (let i = 0; i < option.length; i++) {
					var last = result[i]; //把选中的值存放到字符串last去
					var isShow = [];
					for (var k = 0; k < option[i].value.length; k++) {
						result[i] = option[i].value[k].spec_value_id; //赋值，存在直接覆盖，不存在往里面添加id值
						option[i].value[k].isShow = this.isMay(result); //在数据里面添加字段isShow来判断是否可以选择
						isShow[k] = option[i].value[k].isShow;
					}
					this.isShows[i] = isShow;
					// console.log(this.isShows[i]+"-"+i)
					result[i] = last; //还原，目的是记录点下去那个值，避免下一次执行循环时避免被覆盖
				}
				// console.log("isShows:"+this.isShows)
				//重绘
				this.gspecList.spec_info_list = [];
				this.$set(this.gspecList, 'spec_info_list', option);
				this.getinfo(this.selectArr);
				this.$forceUpdate();
			},
			// 获取选择的值
			getinfo: function(item) {
				var checked = item.join('_');
				if (this.shopItemInfo[checked]) {
					this.goodsInfoNew = this.shopItemInfo[checked];
					this.skutitlename = '已选择：' + this.shopItemInfo[checked].title;
					this.skuId = this.shopItemInfo[checked].id;
				} else {
					this.goodsInfoNew = {};
					var skutitle = [];
					for (var i = 0; i < this.skutitlenamelist.length; i++) {
						if (this.skutitlenamelist[i]) {
							skutitle.push(this.skutitlenamelist[i]);
						}
					}
					this.skutitlename = '请选择 ' + skutitle.toString(',');
					this.skuId = '';
				}
			},
			/**
			 * 判断库存是否为0
			 */
			isMay: function(result) {
				for (var i in result) {
					if (result[i] == '') {
						return true; //如果数组里有为空的值，那直接返回true
					}
				}
				result = result.join('_');
				if (!this.shopItemInfo[result]) {
					return false;
				}
				return this.shopItemInfo[result].stock == 0 ? false : true; //匹配选中的数据的库存，若不为空返回true反之返回false
			},
			// 阻止默认事件
			stopPrevent() {},
			//规格弹窗开关
			toggleSpec() {
				var self = this;

				var skutitle = [];
				for (var i of self.gspecList.goods_spec) {
					self.shopItemInfo[i.specs] = i;
					//修改数据结构格式，改成键值对的方式，以方便和选中之后的值进行匹配
				}

				for (var j of self.gspecList.spec_info_list) {
					self.skutitlenamelist.push(j.spec_name)
					//存储规格标题
				}
				self.checkItem();
				if (this.specClass === 'show') {
					this.specClass = 'hide';

					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
				} else if (this.specClass === 'none') {

					this.specClass = 'show';

				}
				this.$forceUpdate()
			},
			// 点击完成事件
			submitnew: function(e) {
				this.token = uni.getStorageSync('token');
				var pitchOn; //选中的商品规格
				for (var i = 0; i < this.gspecList.goods_spec.length; i++) {
					if (this.skuId == this.gspecList.goods_spec[i].id) {
						pitchOn = this.gspecList.goods_spec[i]
					}
				}
				if (this.skuId) {
					if (this.count > pitchOn.stock) {
						uni.showToast({
							icon: 'none',
							title: "库存不足！"
						})
						return;
					}
					uni.showLoading({
						title: '请稍等...',
						mask: true
					})
					if (e == "buy") {
						uni.hideLoading();
						var orderArr = []; //订单数据
						var commodity = {
							count: this.count, //购买数量
							product_specs: pitchOn.title, //商品规格
							order_quantity: this.product.order_quantity, //是否限制下单
							main_image: this.product.main_image, //主图
							title: this.product.title, //标题
							commodity_id: this.product.id, //商品id
							product_id: pitchOn.id //规格id
						}
						var commdityObj;
						if (this.orderType == 1) {

							let price = {
								product_price: uni.getStorageSync('seckillPrice') || 0
							}
							commdityObj = Object.assign(commodity, price)

						} else {
							let price = {
								product_price: pitchOn.price * 100
							}
							commdityObj = Object.assign(commodity, price)

						}
						orderArr.push(commdityObj);
						uni.setStorageSync("orderArr", orderArr);

						uni.navigateTo({
							url: '/pages/submit/submit?isShoppingTrolley=0'
						})
						this.specClass = 'none'; //关闭弹出层
					} else {
						//加入购物车
						this.$http('goods.shoppingTrolleyAdd', {
							product_id: this.product.id,
							product_specs_id: this.skuId,
							token: this.token
						}).then(res => {
							uni.hideLoading();
							if (res.code == 200) {
								uni.showToast({
									icon: 'none',
									title: res.msg
								})
								this.specClass = 'none'; //关闭弹出层
							} else {
								uni.showToast({
									icon: 'none',
									title: res.msg
								})
							}
						})
					}
				} else {
					uni.showToast({
						title: '请选择规格',
						mask: false,
						duration: 1500
					});
				}

			},
			countUpdate: function(arr) {
				this.count = arr.value;
			}
		}
	};
</script>

<style lang="scss">
	.content {
		z-index: 999999;
	}

	.count {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-top: 10rpx;
		justify-content: space-between;
		padding: 20rpx 5px;
		padding-right: 70rpx;
	}

	.count .title {
		font-size: 15px;
		color: #606266;

	}

	.count .function {
		font-size: 15px;
		color: #606266;


	}

	.buttons {
		display: flex;
		flex-direction: row;
		// justify-content: space-between;
		width: 100%;
		position: fixed;
		left: 0rpx;
		bottom: 0rpx;
		font-size: 28rpx;
		.btn-join {
			background: linear-gradient(135.25deg, #ffcf01 0%, #ffbf00 100%);
			flex: 1;
			min-width: 50vw;
			margin: 0rpx;
			border-radius: 0rpx;
			height: 90rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: none;
			color: #fff;
		}

		.btn-buy {
			background-color: #e20000;
			flex: 1;
						min-width: 50vw;
			// margin: 0rpx;
			border-radius: 0rpx;
			height: 90rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #fff;
			border: none;
		}
	}


	/* 规格选择弹窗 */
	.attr-content {
		padding: 10rpx 30rpx;

		.a-t {
			display: flex;

			image {
				width: 170rpx;
				height: 170rpx;
				flex-shrink: 0;
				margin-top: -40rpx;
				border-radius: 8rpx;
			}

			.right {
				display: flex;
				flex-direction: column;
				padding-left: 24rpx;
				font-size: 26rpx;
				color: #606266;
				line-height: 42rpx;

				.price {
					font-size: 32rpx;
					color: #ff201f;
					margin-bottom: 10rpx;
				}

				.selected-text {
					margin-right: 10rpx;
				}
			}
		}

		.attr-list {
			display: flex;
			flex-direction: column;
			font-size: 30rpx;
			color: #606266;
			padding-top: 30rpx;
			padding-left: 10rpx;

		}

		.item-list {
			padding: 20rpx 0 0;
			display: flex;
			flex-wrap: wrap;

			text {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #eee;
				margin-right: 20rpx;
				margin-bottom: 20rpx;
				border-radius: 100rpx;
				min-width: 60rpx;
				height: 60rpx;
				padding: 0 20rpx;
				font-size: 28rpx;
				color: #303133;
			}

			.selected {
				background-color: rgb(237, 63, 20);
				color: #FFFFFF;
			}

			.noneActive {
				color: #cfcfcf;
				background-color: rgba(0, 0, 0, 0.1);
			}
		}
	}

	/*  弹出层 */
	.popup {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 99;

		&.show {
			display: block;

			.mask {
				animation: showPopup 0.2s linear both;
			}

			.layer {
				animation: showLayer 0.2s linear both;
				padding-bottom: 90rpx;
			}
		}

		&.hide {
			.mask {
				animation: hidePopup 0.2s linear both;
			}

			.layer {
				animation: hideLayer 0.2s linear both;
			}
		}

		&.none {
			display: none;
		}

		.mask {
			position: fixed;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 1;
			background-color: rgba(0, 0, 0, 0.4);
		}

		.layer {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			min-height: 40vh;
			border-radius: 10rpx 10rpx 0 0;
			background-color: #fff;

			.btn {
				height: 66rpx;
				line-height: 66rpx;
				border-radius: 100rpx;
				width: 40%;
				box-sizing: border-box;
				background: #fa436a;
				font-size: 30rpx;
				color: #fff;

			}
		}

		@keyframes showPopup {
			0% {
				opacity: 0;
			}

			100% {
				opacity: 1;
			}
		}

		@keyframes hidePopup {
			0% {
				opacity: 1;
			}

			100% {
				opacity: 0;
			}
		}

		@keyframes showLayer {
			0% {
				transform: translateY(120%);
			}

			100% {
				transform: translateY(0%);
			}
		}

		@keyframes hideLayer {
			0% {
				transform: translateY(0);
			}

			100% {
				transform: translateY(120%);
			}
		}
	}
</style>
